﻿using DimensionsHelper.Common.Contracts.TableFormatter;
using DimensionsHelper.Common.Contracts.TableFormatter.Options;
using DimensionsHelper.Common.Contracts.Excel;
using DimensionsHelper.Services.TableFormatter;

namespace DimensionsHelper.Client.WinUi.ViewModels;

public partial class TableFormatterViewModel : ProjectViewModel<TableFormatterOptions>
{
    public StringPairCollection Replacements { get; } = [];


    public override string Section => ResourceKeys.TableFormatterDisplayName.GetLocalized();


    protected override string SettingsKey => "TableFormatter";


    protected override JsonTypeInfo<TableFormatterOptions> JsonTypeInfo =>
        ServiceJsonContext.Default.TableFormatterOptions;


    protected override bool OnProjectObjectPreparing(IReportService reportService)
    {
        TableFormatterFilesViewModel inputs = App.GetService<TableFormatterFilesViewModel>();

        if (inputs.AnyValidFile())
        {
            return true;
        }

        reportService.Error("未指定有效的输入和输出文件");
        return false;
    }


    protected override void OnProjectObjectStarting(IProjectBase<TableFormatterOptions> projectObject,
        CancellationToken cancellationToken)
    {
        TableFormatter formatter = (TableFormatter)projectObject;

        foreach ((string fileName, IReadOnlyList<TableInputFileInfo> inputs) in App
                     .GetService<TableFormatterFilesViewModel>()
                     .GetOutputFiles())
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (string.IsNullOrEmpty(fileName) || inputs.Count == 0)
            {
                continue;
            }

            IExcelWorkbookOperator workbook = App.GetService<IExcelWorkbookOperator>();
            workbook.Create(fileName);
            formatter.Execute(workbook, inputs, cancellationToken);
        }
    }


    protected override void LoadOption(TableFormatterOptions source, IReportService reportService)
    {
        Replacements.FromDictionary(source.TextReplacements);
        App.GetService<TableReorderMapViewModel>().FromDictionary(source.TablesReordering);
        App.GetService<TableFormatterTableOptionsViewModel>().LoadOption(source, reportService);
    }


    protected override bool TryWriteOption(TableFormatterOptions target, IReportService reportService)
    {
        Replacements.ToDictionary(target.TextReplacements);
        App.GetService<TableReorderMapViewModel>().ToDictionary(target.TablesReordering);
        return App.GetService<TableFormatterTableOptionsViewModel>().TryWriteOptions(target, reportService);
    }


    protected override IProjectBase<TableFormatterOptions> GetProjectObject() => App.GetService<ITableFormatter>();
}